package cn.edu.bjtu.toychange.dao;

import java.util.ArrayList;

import org.hibernate.Session;

import cn.edu.bjtu.toychange.entity.Requisition;

public class RequisitionDao extends BaseDao {
	private Session session;
	
	public RequisitionDao() {
		session = getSession();
	}
	
	// 添加或修改requisition
	public boolean saveRequisition(Requisition requisition) {
		session.beginTransaction();
		try {
			session.saveOrUpdate(requisition);
		} catch (Exception e) {
			return false;
		}
		
		session.close();
		
		return true;
	}

	// 删除requisition
	public boolean deleteRequisition(int requisitionID) {

		session.beginTransaction();
		try {
			session.delete(session.load(Requisition.class, requisitionID));
		} catch (Exception e) {
			return false;
		}
		
		session.close();
		
		return true;
	}

	// 获取Requisition
	public Requisition getRequisition(int requisitionID) {
		return (Requisition) session.get(Requisition.class, requisitionID);
	}
	
	//处理Requisition
	public boolean dealRequisition(int requisitionID, boolean deal) {
		Requisition requisition = new Requisition();
		
		try {
			requisition = getRequisition(requisitionID);
			this.saveRequisition(requisition);
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Requisition> getUserSendRequisitions(int userID) {
		// TODO Auto-generated method stub
		session.beginTransaction();
		ArrayList<Requisition> requisitionList = (ArrayList<Requisition>) session.createQuery("SELECT * FROM requisition WHERE R_senderID = ?")
				.setInteger(0, userID).list();
		session.close();
		
		return requisitionList;
	}
                                                                          
		@SuppressWarnings("unchecked")
		public ArrayList<Requisition> getUserReceiveRequisitions(int userID) {
		// TODO Auto-generated method stub
		
		session.beginTransaction();
		ArrayList<Requisition> requisitionList = (ArrayList<Requisition>) session
				.createQuery("SELECT * FROM requisition WHERE R_receiverID = ?")
				.setInteger(0, userID).list();
		session.close();

		return requisitionList;
	}
}
